package com.pxst.agent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import com.pxst.agent.entity.SysAgents;
import com.pxst.agent.entity.SysAgentCommissionSettings;
import com.pxst.agent.entity.SysRebateScheme;
import com.pxst.agent.mapper.SysAgentsMapper;
import com.pxst.agent.mapper.SysAgentCommissionSettingsMapper;
import com.pxst.agent.mapper.SysRebateSchemeMapper;
import com.pxst.agent.req.AgentCommissionReq;
import com.pxst.agent.req.AgentReq;
import com.pxst.agent.req.AgentCreatReq;
import com.pxst.agent.req.AgentUpdateReq;
import com.pxst.agent.resp.*;
import com.pxst.agent.service.SysAgentsService;
import com.pxst.merchant.entity.SysMerchantInfo;
import com.pxst.merchant.mapper.SysMerchantInfoMapper;
import com.pxst.resp.ApiResp;
import com.pxst.utils.RandomStringGenerator;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author zarke
* @since 2023-09-08 11:13:03
*/
@Service
@Transactional
@Slf4j
public class SysAgentsServiceImpl extends JoinServiceImpl<SysAgentsMapper, SysAgents> implements SysAgentsService {

    @Autowired
    private SysAgentsMapper sysAgentsMapper;

    @Autowired
    private SysMerchantInfoMapper sysMerchantInfoMapper;

    @Autowired
    private SysAgentCommissionSettingsMapper systemAgentCommissionSettingsMapper;

    @Autowired
    private SysRebateSchemeMapper systemRebateSchemeMapper;

    /**
     * 代理下拉框信息
     * @return
     */
    @Override
    public ApiResp<AgentResp> getAgentList(Integer status) {
        //先查出所有的代理信息
        List<SysAgents> list = new ArrayList<>();
        if (status == null){
            list = sysAgentsMapper.selectList(null);
        }else if (status == 1){
            list = sysAgentsMapper.selectList(new LambdaQueryWrapper<SysAgents>()
                    .eq(SysAgents::getStatus , status));
        }
        if (list.size() == 0){
            return ApiResp.sucess(new AgentResp());
        }
        //创建返回类，将类型为总代信息进行查询存贮
        List<AgentResp> collect = list.stream().map(iter -> {
            AgentResp agentResp = new AgentResp();
            if (iter.getIdentity() != null && iter.getIdentity() == 2) {
                BeanUtils.copyProperties(iter, agentResp);
                SysAgents byId = sysAgentsMapper.selectById(iter.getBelongId());
                if (byId != null) {
                    agentResp.setTopAgentId(byId.getDisplayId());
                    agentResp.setTopAgentName(byId.getFullName());
                }
            } else if (iter.getIdentity() == null || iter.getIdentity() == 1) {
                BeanUtils.copyProperties(iter, agentResp);
            }
            return agentResp;
        }).collect(Collectors.toList());
        return ApiResp.sucess(collect);
    }

    /**
     * 搜索
     * @return
     */
    @Override
    public ApiResp<AgentSearchResp> getAgents(AgentReq agentReq) {
        //先搜索出所有符合条件的代理信息
        LambdaQueryWrapper<SysAgents> lam = new LambdaQueryWrapper<SysAgents>();
        if (agentReq.getIdentity() != null && agentReq.getIdentity() == 0){
            lam.isNull(SysAgents::getIdentity);
        }else {
            if (agentReq.getBelongId() != null ){
                lam.eq(SysAgents::getBelongId,agentReq.getBelongId());
            }
            if (agentReq.getAgentId() != null){
                lam.eq(SysAgents::getId,agentReq.getAgentId());
            }
            if (agentReq.getStatus() != null){
                lam.eq(SysAgents::getStatus,agentReq.getStatus());
            }
        }
        PageHelper.startPage(agentReq.getPage(),agentReq.getRp());
        Page<SysAgents> page = (Page<SysAgents>) sysAgentsMapper.selectList(lam);

        //将查询结果进行处理
        List<AgentSearchResp> collect = page.getResult().stream().map(iter -> {
            AgentSearchResp agentResp1 = new AgentSearchResp();
            BeanUtils.copyProperties(iter, agentResp1);
            if (iter.getIdentity() != null && iter.getIdentity() == 1) {
                //是总代就去查询下面的代理信息
                List<SysAgents> sysAgents = sysAgentsMapper.selectList(new LambdaQueryWrapper<SysAgents>().eq(SysAgents::getBelongId, iter.getId()));
                if (sysAgents.size() > 0) {
                    List<Crews> crewsList = sysAgents.stream().map(crew -> {
                        Crews crews = new Crews();
                        crews.setId(crew.getId());
                        crews.setFullName(crew.getFullName());
                        return crews;
                    }).collect(Collectors.toList());
                    agentResp1.setCrews(crewsList);
                }
            }
            return agentResp1;
        }).collect(Collectors.toList());

        //将data信息进行封装
        return ApiResp.page(page.getPageNum(),page.getPageSize(), (int) page.getTotal(),collect);
    }

    /**
     * 新增
     * @param agentReq1
     * @return
     */
    @Override
    public ApiResp<SysAgents> create(AgentCreatReq agentReq1) {
        SysAgents sysAgents = new SysAgents();
        BeanUtils.copyProperties(agentReq1,sysAgents);
        sysAgents.setPassword(RandomStringGenerator.generateRandomString(8));
        sysAgents.setMerchantCount(0L);
        sysAgentsMapper.insert(sysAgents);
        return ApiResp.sucess(sysAgentsMapper.selectById(sysAgents.getId()));
    }

    /**
     * 重置密码
     */
    @Override
    public ApiResp<Map<String,String>> updatePassword(Long id) {
        SysAgents sysAgents = new SysAgents();
        String password = RandomStringGenerator.generateRandomString(8);
        sysAgents.setPassword(password);
        sysAgents.setId(id);
        sysAgentsMapper.updateById(sysAgents);
        Map<String,String> map = new HashMap<>();
        map.put("password",password);
        return ApiResp.sucess(map);
    }

    /**
     * 编辑详情
     * @param updateReq
     * @return
     */
    @Override
    public ApiResp<AgentUpdateReq> updateDetails(AgentUpdateReq updateReq) {
        SysAgents sysAgents = new SysAgents();
        BeanUtils.copyProperties(updateReq,sysAgents);
        sysAgentsMapper.updateById(sysAgents);
        return ApiResp.sucess(updateReq);
    }

    /**
     * 搜索代理抽成
     * @param agentReq
     * @param id
     * @return
     */
    @Override
    public ApiResp<AgentCommissionResp> getAgentCommission(Long id , AgentCommissionReq agentReq) {
        //首先通过id查询代理信息
        SysAgents sysAgents = sysAgentsMapper.selectById(id);
        //创建返回类，拷贝属性
        AgentCommissionResp agentCommissionResp = new AgentCommissionResp();
        BeanUtils.copyProperties(sysAgents,agentCommissionResp);

        //通过代理id和条件去查询商户信息表
        LambdaQueryWrapper<SysMerchantInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysMerchantInfo::getAgentId,id);
        if (agentReq.getMerchantIds() != null && agentReq.getMerchantIds().size() > 0){
            lqw.in(SysMerchantInfo::getId,agentReq.getMerchantIds());
        }
        if (agentReq.getCurrency() != null && !agentReq.getCurrency().isEmpty()){
            lqw.eq(SysMerchantInfo::getCurrency,agentReq.getCurrency());
        }
        List<SysMerchantInfo> sysMerchantInfos = sysMerchantInfoMapper.selectList(lqw);

        //创建二级返回类，并拷贝商户属性
        if (sysMerchantInfos != null && sysMerchantInfos.size() > 0){
            List<PlanSummary> collect = sysMerchantInfos.stream().map(iter -> {
                PlanSummary planSummary = new PlanSummary();
                BeanUtils.copyProperties(iter, planSummary);
                planSummary.setMerchantId(iter.getId());
                //通过代理id和商户id查询，存放抽成设定信息
                SysAgentCommissionSettings systemAgentCommissionSettings = systemAgentCommissionSettingsMapper.selectOne(new LambdaQueryWrapper<SysAgentCommissionSettings>()
                        .eq(SysAgentCommissionSettings::getAgentId, iter.getAgentId()).eq(SysAgentCommissionSettings::getMerchantId, iter.getId()));
                if (systemAgentCommissionSettings != null) {
                    //如果查询出来有对应的抽成设定信息，创建三级返回类，进行拷贝
                    CurrentRebate currentRebate = new CurrentRebate();
                    BeanUtils.copyProperties(systemAgentCommissionSettings, currentRebate);
                    //判断其中的四种回扣方案是否有值，如果有值代表有对应的回扣方案信息(1.银行回扣方案 2.QR回扣方案 3.true wallet回扣方案 4.代付回扣方案)
                    if (currentRebate.getBdrsRpId() != null) {
                        //查询回扣方案表,存在就将回扣方案放入三级返回类中
                        SysRebateScheme systemRebateScheme = systemRebateSchemeMapper.selectById(currentRebate.getBdrsRpId());
                        if (systemRebateScheme != null) {
                            currentRebate.setBankDepositRebatePlan(systemRebateScheme);
                        }
                    }
                    if (currentRebate.getQdrsRpId() != null) {
                        //查询回扣方案表,存在就将回扣方案放入三级返回类中
                        SysRebateScheme systemRebateScheme = systemRebateSchemeMapper.selectById(currentRebate.getQdrsRpId());
                        if (systemRebateScheme != null) {
                            currentRebate.setQrDepositRebatePlan(systemRebateScheme);
                        }
                    }
                    if (currentRebate.getTwdrsRpId() != null) {
                        //查询回扣方案表,存在就将回扣方案放入三级返回类中
                        SysRebateScheme systemRebateScheme = systemRebateSchemeMapper.selectById(currentRebate.getTwdrsRpId());
                        if (systemRebateScheme != null) {
                            currentRebate.setTrueWalletDepositRebatePlan(systemRebateScheme);
                        }
                    }
                    if (currentRebate.getWrsRpId() != null) {
                        //查询回扣方案表,存在就将回扣方案放入三级返回类中
                        SysRebateScheme systemRebateScheme = systemRebateSchemeMapper.selectById(currentRebate.getWrsRpId());
                        if (systemRebateScheme != null) {
                            currentRebate.setWithdrawRebatePlan(systemRebateScheme);
                        }
                    }
                    //将抽成设定信息放入返回类中
                    planSummary.setCurrentRebate(currentRebate);
                }
                return planSummary;
            }).collect(Collectors.toList());
            agentCommissionResp.setPlanSummary(collect);
        }
        return ApiResp.sucess(agentCommissionResp);
    }

}